/*
 * Created by Federico Pisarello - SisDev Software (c) 2013 - fpisarello@sisdevsoft.com
 */

var popForm = 'clientesPop.php';
var actionForm = 'clientesAction.php';

var joDataCliente;
var oTable;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var action = undefined;

function $_init()
{	
	var gaiSelected;
	
	$(document).ready(function() {
		oTable = $('#dt_clientes');
    	oTable.dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bAutoWidth": false,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?accion=search",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null
					  		],
			        fnPreDrawCallback: function () {
			            // Initialize the responsive datatables helper once.
			            if (!responsiveHelper) {
			                responsiveHelper = new ResponsiveDatatablesHelper(oTable, breakpointDefinition);
			            }
			        },
			        fnRowCallback  : function (nRow) {
			            responsiveHelper.createExpandIcon(nRow);
			        },
			        fnDrawCallback : function (oSettings) {
			            responsiveHelper.respond();
			        }
				});
    	
    	/* Click event handler */
    	$('#dt_clientes tbody').on('click', 'tr', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	        }
	        else {
	            oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$("#clientesDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:600, 
		modal: true,
		closeOnEscape: false,
		position : ['center',10],		
		dialogClass:'no-close',
		beforeClose: function() { $_ClearClientesPopForm(); },
		open: function() {
			$('#clientesDialog').css('background-color','#EEEEEE');
		}
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAgregar").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEditar').click( function(e) {
		editProxyShow();
	});
	
	$('#btnEliminar').click( function(e) {
		delProxyShow();
	});
}

function $_initPop()
{
	//Add Click for All Buttons in Pop Form
	$('#btnCerrar').click( function(e) {
		$('#clientesDialog').dialog('close');
	});
	$('#btnGuardar').click( function(e) {
		$('#clientesPopForm').submit();
	});
	
	$('#cuit').mask('99-99999999-9');
	$('.numeric').numeric();
	
	var idTipoIva;
	
	//Populate User Data	
	if(action == iConst.EDIT)
	{
		$('#razonSocial').val(joDataCliente.razonSocial);
		$('#nombreFantasia').val(joDataCliente.nombreFantasia);
		idTipoIva = joDataCliente.idTipoIva
		$('#cuit').val(joDataCliente.cuit);
		$('#telefono').val(joDataCliente.telefono);
		$('#eMail').val(joDataCliente.eMail);
		$('#condVta').val(joDataCliente.condVta);
		$('#bonif').val(joDataCliente.bonif);
		$('#subFacturacion').val(joDataCliente.subFacturacion);
		idUsuarioVendedor = joDataCliente.idUsuarioVendedor;
		$('#comision').val(joDataCliente.comision);
		
		//Direccion Comercial
		$('#direccion').val(joDataCliente.direccion);
		$('#localidad').val(joDataCliente.localidad);
		$('#provincia').val(joDataCliente.provincia);
		$('#codPostal').val(joDataCliente.codPostal);

		//Direccion Entrega
		$('#direccionEntrega').val(joDataCliente.direccionEntrega);
		$('#localidadEntrega').val(joDataCliente.localidadEntrega);
		$('#provinciaEntrega').val(joDataCliente.provinciaEntrega);
		$('#codPostalEntrega').val(joDataCliente.codPostalEntrega);

		$('#cmbIVA').attr('disabled', true);
	}
	
	$_ValidatorSetDefaults();
	$_initPopValidator();
	
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'accion=getTiposIva', 
	    dataType: 'json', 
	    success: function(json) {
	    	$('#cmbIVA').append($('<option>').text('...').attr('value', ''));
	        $.each(json, function(i, value) {
	        	if(value.idTipoIva == idTipoIva)
	        		$('#cmbIVA').append($('<option selected>').text(value.descripcion).attr('value', value.idTipoIva));
	        	else
	        		$('#cmbIVA').append($('<option>').text(value.descripcion).attr('value', value.idTipoIva));
	        });
	    }
	});
	
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'accion=getUsuariosVendedor', 
	    dataType: 'json', 
	    success: function(json) {
	    	$('#cmbVendedor').append($('<option>').text('...').attr('value', ''));
	        $.each(json, function(i, value) {
	        	if(value.idUsuario == idUsuarioVendedor)
	        		$('#cmbVendedor').append($('<option selected>').text(value.nombreCompleto).attr('value', value.idUsuario));
	        	else
	        		$('#cmbVendedor').append($('<option>').text(value.nombreCompleto).attr('value', value.idUsuario));
	        });
	    }
	});
}

function addProxyShow()
{
	//Reset State of action and IndexPK
	actionPK = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	$('#clientesDialog').load(popForm).dialog('open');
}

function editProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', 'Seleccione un Cliente de la Grilla');
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "accion=" + iConst.EDIT + "&idCliente=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataCliente = jsonObj;
        						//Open Pop Dialog
        						$('#clientesDialog').load(popForm).dialog('open');
                            }
        });
	
return true;
}

function $_saveCliente(action)
{
	$("#btnGuardar").attr('disabled','disabled');
	
	var paramData = 'accion=addOrEdit&' + $("#clientesPopForm").serialize();
	
	if(action == iConst.EDIT)
		paramData += '&idCliente=' + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#clientesDialog').dialog('close');
				oTable.fnStandingRedraw();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
            $("#btnGuardar").removeAttr('disabled');
        }
    });

return true;
}

function delProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', 'Seleccione un Cliente de la Grilla');
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deleteClientesDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#deleteClientesDialog').css('background-color','#EEEEEE');
			$('#btnConfirmaEliminar').click( function(e) {
				$_del();
			});
			$('#btnSalirEliminar').click( function(e) {
				$('#deleteClientesDialog').dialog('close')
			})
		}
	});
	$('#deleteClientesDialog').dialog('open');	
}

function $_del()
{
	var paramData = 'accion=' + action + '&idCliente=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){
										$_showMessage('OK', 'OK', jsonObj.msg);
										
										//Reset State of action and IndexPK
										actionPK = undefined;
										action = iConst.NEW;
										oTable.fnStandingRedraw();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deleteClientesDialog').dialog('close');
                                }
            });

return true;
}

function $_initPopValidator()
{
	$('#clientesPopForm').validate({
		submitHandler: function() {
			$_saveCliente(action);
		}, 		
		rules: {
			razonSocial: {required: true,minlength: 1},
			cmbIVA: {required: true,minlength: 1},
			cuit: {required: true,minlength: 1},
			direccion: {required: true,minlength: 1},
			telefono: {required: true,minlength: 1}
		},
		messages: {
			razonSocial: {required: '',minlength: ''},
			cmbIVA: {required: '',minlength: ''},
			cuit: {required: '',minlength: ''},
			direccion: {required: '',minlength: ''},
			telefono: {required: '',minlength: ''}
		}
	});
}

function $_ClearClientesPopForm()
{	
	$("#clientesDialog").empty();
}